<script lang="ts" setup>
import {
    Discount,
    Edit,
    InfoFilled,
    Message,
    More,
    Select,
    SemiSelect,
    View,
    Hide
} from '@element-plus/icons-vue'
import { ref, onMounted, Ref, reactive, watch } from 'vue'
import { useRoute } from 'vue-router';
import useApplicantStore from '@/stores/applicantStore'
import { getCaseByUserId, updateByApplicant, addCaseRepayment, getCaseRepayment, sendApplyRequest } from "@/axios/case/caseReq";
import { Case, CaseStatus } from '@/types/response/case';
import useUserStore from '@/stores/userStore';
import { getRespondentById } from "@/axios/respondent/respondentReq";
import { TimeUtil } from '@/utils/timeUtil'
import Repayment from '@/types/response/repayment';
import { getRepaymentListByInsId } from '@/axios/case/repaymentReq'
import Notice from '@/utils/notice';
import { ca, tr } from 'element-plus/es/locale';
import { cu } from '@fullcalendar/core/internal-common';
import viewRepayment from '@/compontent/viewRepayment.vue';

const applicantStore = useApplicantStore()
const caseInfoDialog = ref(false)
const choseRepayDialog = ref(false)
const userStore = useUserStore()
const route = useRoute()
const choseRepay = ref([])
type Mycaseinfo = {
    name: string,
    idNum: string,
    mediateState: string,
    mediateTime: string,
    caseStatus: number,
    caseIndex:number
}
const repayments: Ref<Repayment[]> = ref([])
const caseinfos: Ref<Mycaseinfo[]> = ref([])
const hideCaseinfos: Ref<Mycaseinfo[]> = ref([])
const currentCaseInfos: Ref<Mycaseinfo[]> = ref([])
let caseinfo: Case = new Case();
//控制添加弹窗
const canEdit = ref(false)

let applicantId = null
let applicantInsId = null
let cases: Ref<Case[]> = ref([])
let outerCaseId = null
onMounted(async () => {
    applicantId = userStore.userId
    applicantInsId = applicantStore.applicantInsId
    cases.value = await getCaseByUserId(applicantId)
    for (let i = 0; i < cases.value.length; i++) {
        let rsp = cases.value[i].respondent
        let mediateStateinfo = CaseStatus.getCommentByStatus(cases.value[i].caseState)
        caseinfos.value.push({
            name: rsp.name,
            idNum: rsp.idNum,
            mediateState: mediateStateinfo,
            mediateTime: cases.value[i].mediationTime == null ? '待定' : cases.value[i].mediationTime,
            caseStatus: cases.value[i].caseState,
            caseIndex:i
        })
    }
    hideCaseinfos.value = caseinfos.value.filter((item) => {
            return item.caseStatus != CaseStatus.nullify && item.caseStatus != CaseStatus.inject
        })
    currentCaseInfos.value = hideCaseinfos.value
})
const calculateTotalAmount = () => {
    if (caseinfo.debt.principal != null
        && caseinfo.debt.principal != 0
        && caseinfo.debt.loanDate != null
        && caseinfo.debt.repayDate != null
    ) {

        // 简单的计算示例，可以根据实际需求调整
        const principal = caseinfo.debt.principal
        const annualRate = caseinfo.debt.annualRate
        const overdueRate = caseinfo.debt.overdueRate || 0
        const lateFee = caseinfo.debt.lateFee || 0
        const penalty = caseinfo.debt.liquidated || 0
        const serviceFee = caseinfo.debt.commission || 0
        const otherFees = caseinfo.debt.otherFee || 0

        // 计算还款总金额
        let totalAmount = 0
        let interest = 0
        let extraInterest = 0

        if (TimeUtil.timeCmp(new Date(), TimeUtil.strToDate(caseinfo.debt.repayDate)) <= 0) {
            let days = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.loanDate), new Date())
            interest = (principal * annualRate / 100) * days / 365;
            totalAmount = principal + interest + extraInterest + overdueRate + lateFee + penalty + serviceFee + otherFees
        }
        else {
            let days = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.loanDate), TimeUtil.strToDate(caseinfo.debt.repayDate))
            let fineDays = TimeUtil.getDayComputed(TimeUtil.strToDate(caseinfo.debt.repayDate), new Date())
            interest = (principal * annualRate / 100) * days / 365;
            extraInterest = (principal * annualRate / 100) * fineDays / 365 * (1 + overdueRate / 100);
            totalAmount = principal + interest + extraInterest + overdueRate + lateFee + penalty + serviceFee + otherFees
        }
        caseinfo.debt.amount = parseFloat(totalAmount.toFixed(2))
        caseinfo.debt.interest = parseFloat(interest.toFixed(2))
        caseinfo.debt.extraInterest = parseFloat(extraInterest.toFixed(2))
    }
}
// 监听表单字段的变化，自动计算还款总金额
watch(
    () => [
        caseinfo.debt.principal,
        caseinfo.debt.annualRate,
        caseinfo.debt.overdueRate,
        caseinfo.debt.lateFee,
        caseinfo.debt.liquidated,
        caseinfo.debt.commission,
        caseinfo.debt.otherFee,
        caseinfo.debt.loanDate,
        caseinfo.debt.repayDate
    ],
    calculateTotalAmount
)
const onSubmit = async () => {
    try {
        await updateByApplicant(caseinfo);
        /*   console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
          console.log(caseinfo) */
        /* await addCaseRepayment(caseinfo.caseId, choseRepay.value) */
        Notice.success('案件修改成功');
    } catch (error) {
        console.error('提交修改时出错:', error);
        Notice.error('申请案件时出错，请重试');
    }
}
const closeCaseInfoDialog = () => {
    caseInfoDialog.value = false
}
const openChoseRepayDialog = async (index: number) => {
    let caseIndex =  currentCaseInfos.value[index].caseIndex;
    let caseId = cases.value[caseIndex].caseId
    outerCaseId = caseId
    choseRepayDialog.value = true
    let selectedCaseRepayements = await getCaseRepayment(caseId)
    for (let i = 0; i < selectedCaseRepayements.length; i++) {
        choseRepay.value.push(selectedCaseRepayements[i].repaymentId)
    }
    repayments.value = await getRepaymentListByInsId(applicantInsId)
}
const updateCaseInfo = (index: number) => {
    let caseIndex =  currentCaseInfos.value[index].caseIndex;
    caseInfoDialog.value = true
    caseinfo = reactive(cases.value[caseIndex])
    canEdit.value = false
}
const ViewCaseInfo = async (index: number) => {
    let caseIndex =  currentCaseInfos.value[index].caseIndex;
    caseInfoDialog.value = true
    canEdit.value = true
    caseinfo = reactive(cases.value[caseIndex])
}
const changeRepayment = async () => {
    try {
        await addCaseRepayment(outerCaseId, choseRepay.value)
        choseRepayDialog.value = false
        Notice.success('修改成功')
    } catch (error) {
        Notice.error('修改失败，请重试')
        console.error('修改还款方案时出错：', error)
    }
}
const applyCase = async (index: number) => {
    try {
        let caseIndex =  currentCaseInfos.value[index].caseIndex;
        let caseId = cases.value[caseIndex].caseId
        await sendApplyRequest(caseId);
        Notice.success('申请成功')
        cases.value[index].caseState = CaseStatus.applied
    } catch (error) {
        Notice.error('申请失败，请重试')
        console.error('申请案件时出错：', error)
    }
}
let injectVisiable = ref(false)
const changeInjectVisiable = () => {
    if (injectVisiable.value) {
        injectVisiable.value = false
        currentCaseInfos.value = hideCaseinfos.value
    }
    else {
        injectVisiable.value = true
        currentCaseInfos.value = caseinfos.value
    }
}
//还款方案详细
const repaymentDetailDialog = ref(false) 
let repaymentDetail = null
const openRepaymentDetailDialog = (repayment: Repayment)=>{
    repaymentDetailDialog.value = true
    repaymentDetail = repayment
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>我的调解</span>
                <div class="inject-wrapper">
                    <span>作废案件</span>
                    <el-button @click="changeInjectVisiable" class="inject-button-wrapper">
                        <el-icon :class="injectVisiable ? 'view-icon' : 'hide-icon'">
                            <component :is="injectVisiable ? View : Hide"></component>
                        </el-icon>
                    </el-button>
                </div>
            </div>

        </template>
        <el-table :data="currentCaseInfos" style="width: 100%">
            <el-table-column type="index" label="序号" width="100"> </el-table-column>
            <el-table-column label="姓名" width="100" prop="name"> </el-table-column>
            <el-table-column label="身份证号" prop="idNum"></el-table-column>
            <el-table-column label="调解时间" prop="mediateTime"></el-table-column>
            <el-table-column label="调解状态" prop="mediateState"></el-table-column>
            <el-table-column label="操作" width="250">
                <template #default="scope">
                    <div class="button-group">
                        <el-button :icon="More" circle plain type="default"
                            @click="ViewCaseInfo(scope.$index)"></el-button>
                        <el-button :icon="Edit" circle plain type="primary"
                            :disabled="scope.row.caseStatus != CaseStatus.unapplied"
                            @click="updateCaseInfo(scope.$index)"></el-button>
                        <el-button :icon="Discount" circle plain type="primary"
                            :disabled="scope.row.caseStatus > CaseStatus.waitChooseRepayment"
                            @click="openChoseRepayDialog(scope.$index)"></el-button>
                        <el-popconfirm width="220" :icon="InfoFilled" icon-color="#626AEF" title="提交后无法修改，确定提交吗？"
                            @confirm="applyCase(scope.$index)">
                            <template #reference>
                                <el-button v-if="scope.row.caseStatus <= CaseStatus.unapplied" :icon="SemiSelect" circle
                                    plain type="primary"></el-button>
                            </template>
                        </el-popconfirm>
                        <div class="custom-button is-success" v-if="scope.row.caseStatus > CaseStatus.unapplied">
                            <el-icon>
                                <Select />
                            </el-icon>
                        </div>
                    </div>

                    <!--  <el-button :icon="Delete" circle plain type="danger"></el-button> -->
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <el-dialog v-model="caseInfoDialog" title="案件信息" width="60%">
            <el-form :model="caseinfo" label-width="auto">
                <el-form-item label="姓名" class="applied-content-down-item-first">
                    <el-input v-model="caseinfo.respondent.name" :disabled="canEdit" />
                </el-form-item>
                <el-form-item label="身份证号">
                    <el-input v-model="caseinfo.respondent.idNum" :disabled="canEdit" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="caseinfo.respondent.phoneNum" :disabled="canEdit" />
                </el-form-item>
                <el-form-item label="本金">
                    <el-input-number v-model="caseinfo.debt.principal" :min="0" :disabled="canEdit"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="年利率">
                    <el-input-number v-model="caseinfo.debt.annualRate" :min="0" :disabled="canEdit" :precision="2"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>%</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="借款时间">
                    <el-col :span="11">
                        <el-date-picker v-model="caseinfo.debt.loanDate" type="date" :disabled="canEdit"
                            placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"
                            @change="calculateTotalAmount" />
                    </el-col>
                </el-form-item>
                <el-form-item label="还款期限">
                    <el-col :span="11">
                        <el-date-picker v-model="caseinfo.debt.repayDate" type="date" :disabled="canEdit"
                            placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"
                            @change="calculateTotalAmount" />
                    </el-col>
                </el-form-item>
                <el-form-item label="逾期利率">
                    <el-input-number v-model="caseinfo.debt.overdueRate" :min="0" :disabled="canEdit" :precision="2"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>%</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="滞纳金">
                    <el-input-number v-model="caseinfo.debt.lateFee" :min="0" :disabled="canEdit"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="违约金">
                    <el-input-number v-model="caseinfo.debt.liquidated" :disabled="canEdit" :min="0"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="手续费">
                    <el-input-number v-model="caseinfo.debt.commission" :disabled="canEdit" :min="0"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>
                <el-form-item label="其他费用">
                    <el-input-number v-model="caseinfo.debt.otherFee" :disabled="canEdit" :min="0"
                        controls-position="right" @change="calculateTotalAmount">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input-number>
                </el-form-item>

                <el-form-item label="还款总金额">
                    <el-input class="total-amount-input" :precision="2" v-model="caseinfo.debt.amount" :min="0"
                        :disabled="true">
                        <template #suffix>
                            <span>RMB</span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="案由" maxlength="10" show-word-limit>
                    <div class="cause-input-wrapper">
                        <div class="cause-input"><el-input v-model="caseinfo.cause" :disabled="canEdit" /></div>
                    </div>
                </el-form-item>
                <div class="button-container">
                    <el-button @click="closeCaseInfoDialog">关闭</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog v-model="choseRepayDialog" title="还款方案" width="25%">
            <el-checkbox-group v-model="choseRepay">
                <div v-for="repayment in repayments" :key="repayment.repaymentId">
                    <div class="repay-checkbox-wrapper">
                        <el-checkbox :label="repayment.ruleName" :value="repayment.repaymentId">
                        </el-checkbox>
                        <div class="repay-checkbox-button">
                            <el-button type="primary" size="small" @click="openRepaymentDetailDialog(repayment)">查看详细</el-button>
                        </div>
                    </div>
                </div>
                <view-repayment v-model="repaymentDetailDialog" :repaymentModel="repaymentDetail"></view-repayment>
            </el-checkbox-group>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="default" @click="choseRepayDialog = false">关闭</el-button>
                    <el-button type="primary" @click="changeRepayment()">修改</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.button-group {
    display: flex;
    align-items: center;
}

.page-container {
    min-height: 100%;
    box-sizing: border-box;
    width: 98%;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.inject-wrapper {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}

.inject-button-wrapper {
  margin-left: 4px; /* 设置与文字的间距 */
  background-color: transparent !important;
  border: none;
  padding: 4px;
  font-size: 20px;
  margin-top: 2px;
}

.view-icon {
  color: #67c23a; /* 可以根据需要调整颜色 */
}

.hide-icon {
  color: #f56c6c; /* 可以根据需要调整颜色 */
}

.custom-button {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    padding: 8px;
    margin-left: 10px;
    margin-right: 12px;
}
.inject-wrapper.el-button {
  border: none !important;

  padding: 0 !important;
}

.inject-wrapper.el-button:hover {
  background-color: transparent !important;
  border: none !important;
}

.inject-wrapper.el-button:focus {
  outline: none !important;
  box-shadow: none !important;
}

.is-success {
    background-color: #67c23a;
    /* Element Plus success color */
    color: white;
}
.repay-checkbox-wrapper{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>